package com.zjhcsoft.zjpr.statistics.job;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import common.Logger;

/**
 * 使用时，必须要嗲用 init 方法与 close() 	、printEnd() 方法
 * 使用时 status 必须一样！
 * 
 * @author Navy
 * 
 */
public class JobLog {
	private static Logger LOG = Logger.getLogger(JobLog.class);
	final static String path = Resoure.get("localUrl");
	static Map<String, FileWriter> namemap = new HashMap<String, FileWriter>();
	
	/**
	 * 初始化
	 * @param status
	 */
	public static void init(String status) {
		final String path = Resoure.get("localUrl");
		if (!new File(path).exists()) {
			new File(path).mkdirs();
		}
		String errorName = null;
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		
		/*
		 * 删除第longtime的日志
		 */
		int longtime = Integer.valueOf(Resoure.get("loglongesttime"));
		String lasttime = sf.format(new Date(System.currentTimeMillis()-longtime*24*60*60*1000));
		
		File lastfile = new File(path+File.separator+"customization_"+lasttime+"_error.log");
		if(lastfile.exists())
			lastfile.delete();
		lastfile = new File(path+File.separator+"receivefax_"+lasttime+"_error.log");
		if(lastfile.exists())
			lastfile.delete();
		
		try {
			if (Resoure.CUSTOMIZATION.equals(status)) {
				errorName = "customization_" + sf.format(new Date())
						+ "_error.log";
				namemap.put(Resoure.CUSTOMIZATION, new FileWriter(new File(path
						+ File.separator + errorName), true));
			} else if (Resoure.RECEIVEFAX.equals(status)) {
				errorName = "receivefax_" + sf.format(new Date())
						+ "_error.log";
				namemap.put(Resoure.RECEIVEFAX, new FileWriter(new File(path
						+ File.separator + errorName), true));
			}
		} catch (IOException e) {
			LOG.error("",e);
		}

	}
	
	/**
	 * 输出
	 * @param string
	 * @param status
	 */
	public static void print(String string, String status) {
		FileWriter fw = namemap.get(status);
		try {
			fw.write(string + "\r\n");
			fw.flush();

		} catch (IOException e) {
			LOG.error("",e);
		}
	}
	
	/**
	 * 输出并且结束
	 * @param string
	 * @param status
	 */
	public static void printEnd(String string, String status) {
		print("-------------------------------------------------------------",
				status);
		print(string, status);
		close(status);
	}
	
	/**
	 * 关闭文件
	 * @param status
	 */
	public static void close(String status) {
		FileWriter fw = namemap.get(status);
		try {
			fw.close();
			namemap.remove(status);
		} catch (IOException e) {
			LOG.error("",e);
		}
	}
}